import React from 'react';
import { Tag, Input, InputNumber, Select, Switch } from 'antd';
import CrudPage from '@/components/CrudPage';
import type { CrudPageProps } from '@/components/CrudPage';
import type { ModalFormItem, SearchFormItem } from '@/components';
import * as api from './api';

const { TextArea } = Input;
const { Option } = Select;

interface OssConfig {
  id: string;
  tenantId?: string;
  name: string;
  type: 'minio' | 'oss' | 's3' | 'local';
  endpoint: string;
  port: number;
  useSsl: boolean;
  accessKey: string;
  secretKey: string;
  bucketName: string;
  region?: string;
  isDefault: boolean;
  isActive: boolean;
  maxFileSize: number;
  allowedTypes?: string;
  remark?: string;
  createdAt: string;
  updatedAt: string;
}

const FileConfigPage: React.FC = () => {
  const formFields: ModalFormItem[] = [
    {
      name: 'name',
      label: '配置名称',
      component: <Input placeholder="例如：生产环境MinIO" />,
      rules: [{ required: true, message: '请输入配置名称' }],
    },
    {
      name: 'type',
      label: '存储类型',
      component: (
        <Select placeholder="请选择存储类型">
          <Option value="minio">MinIO</Option>
          <Option value="oss">阿里云OSS</Option>
          <Option value="s3">AWS S3</Option>
          <Option value="local">本地存储</Option>
        </Select>
      ),
      rules: [{ required: true, message: '请选择存储类型' }],
    },
    {
      name: 'endpoint',
      label: '服务端点',
      component: <Input placeholder="例如：minion.xlcig.cn" />,
      rules: [{ required: true, message: '请输入服务端点' }],
    },
    {
      name: 'port',
      label: '端口',
      component: <InputNumber placeholder="443" style={{ width: '100%' }} />,
      rules: [{ required: true, message: '请输入端口' }],
    },
    {
      name: 'useSsl',
      label: '使用SSL',
      component: <Switch />,
      valuePropName: 'checked',
    },
    {
      name: 'accessKey',
      label: 'Access Key',
      component: <Input placeholder="访问密钥" />,
      rules: [{ required: true, message: '请输入Access Key' }],
    },
    {
      name: 'secretKey',
      label: 'Secret Key',
      component: <Input.Password placeholder="私密密钥" />,
      rules: [{ required: true, message: '请输入Secret Key' }],
    },
    {
      name: 'bucketName',
      label: '桶名称',
      component: <Input placeholder="例如：xux" />,
      rules: [{ required: true, message: '请输入桶名称' }],
    },
    {
      name: 'region',
      label: '区域',
      component: <Input placeholder="例如：us-east-1" />,
    },
    {
      name: 'maxFileSize',
      label: '最大文件大小(MB)',
      component: <InputNumber placeholder="50" min={1} style={{ width: '100%' }} />,
      rules: [{ required: true, message: '请输入最大文件大小' }],
    },
    {
      name: 'allowedTypes',
      label: '允许的文件类型',
      component: <TextArea rows={3} placeholder="多个用逗号分隔，例如：.jpg,.png,.pdf" />,
    },
    {
      name: 'isDefault',
      label: '设为默认',
      component: <Switch />,
      valuePropName: 'checked',
    },
    {
      name: 'isActive',
      label: '启用',
      component: <Switch />,
      valuePropName: 'checked',
    },
    {
      name: 'remark',
      label: '备注',
      component: <TextArea rows={3} placeholder="配置说明" />,
    },
  ];

  const searchFields: SearchFormItem[] = [
    {
      name: 'name',
      label: '配置名称',
      component: <Input placeholder="请输入配置名称" allowClear />,
      col: 6,
    },
    {
      name: 'type',
      label: '存储类型',
      component: (
        <Select placeholder="请选择存储类型" allowClear>
          <Option value="">全部</Option>
          <Option value="minio">MinIO</Option>
          <Option value="oss">阿里云OSS</Option>
          <Option value="s3">AWS S3</Option>
          <Option value="local">本地存储</Option>
        </Select>
      ),
      col: 6,
    },
  ];

  const columns = [
    {
      title: '配置名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (value: string) => {
        const typeMap: Record<string, { text: string; color: string }> = {
          minio: { text: 'MinIO', color: 'blue' },
          oss: { text: '阿里云OSS', color: 'orange' },
          s3: { text: 'AWS S3', color: 'green' },
          local: { text: '本地存储', color: 'default' },
        };
        const config = typeMap[value] || { text: value, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '端点',
      dataIndex: 'endpoint',
      key: 'endpoint',
      width: 200,
      ellipsis: true,
    },
    {
      title: '桶名称',
      dataIndex: 'bucketName',
      key: 'bucketName',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 80,
      render: (value: boolean) => (
        <Tag color={value ? 'success' : 'default'}>{value ? '启用' : '禁用'}</Tag>
      ),
    },
    {
      title: '默认',
      dataIndex: 'isDefault',
      key: 'isDefault',
      width: 80,
      render: (value: boolean) => value && <Tag color="gold">默认</Tag>,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (value: string) => new Date(value).toLocaleString('zh-CN'),
    },
  ];

  const crudConfig: CrudPageProps<OssConfig> = {
    title: 'OSS配置管理',
    fetchApi: async (params: any) => {
      const response = await api.getOssConfigs(params);
      return response;
    },
    createApi: async (data: any) => {
      const response = await api.createOssConfig(data);
      return response;
    },
    updateApi: async (data: any) => {
      // 提取id并移除只读字段
      const { id, createdAt, updatedAt, tenantId, ...updateData } = data;
      const response = await api.updateOssConfig(id, updateData);
      return response;
    },
    deleteApi: async (id: string) => {
      const response = await api.deleteOssConfig(id);
      return response;
    },
    transformBeforeSubmit: (values: any) => {
      // 只移除只读字段，保留id用于更新
      const { createdAt, updatedAt, tenantId, ...submitData } = values;
      return submitData;
    },
    columns,
    formItems: formFields,
    searchItems: searchFields,
    rowKey: 'id',
    enableBatchDelete: false,
  };

  return <CrudPage {...crudConfig} />;
};

export default FileConfigPage;
